use crate::config::AUTH_API_URL;
use crate::models::{CodeSource, ImgCode, LoginInfo, LoginResult, Response};
use crate::result::MyResult;
// use gloo::console;
use crate::errors::MyError;
use gloo_net::http::Request;

pub async fn login(login_info: LoginInfo) -> MyResult<LoginResult> {
    let response = Request::post(&format!("{}/api/auth/login", AUTH_API_URL))
        .json(&login_info)?
        .send()
        .await?;
    if response.status() != 200 {
        Err(MyError::GeneralError(response.text().await?))
    } else {
        Ok(response.json::<Response<LoginResult>>().await?.data)
    }
}

pub async fn register(register_info: LoginInfo) -> MyResult<bool> {
    let response = Request::post(&format!("{}/api/auth/register", AUTH_API_URL))
        .json(&register_info)?
        .send()
        .await?;

    if response.status() != 200 {
        return Err(MyError::GeneralError(response.text().await?));
    }
    Ok(true)
}

// 获取code_source，用code_source来作为参数调用gen_code，来获取验证码图片
pub async fn get_code_source() -> MyResult<String> {
    Ok(
        Request::get(&format!("{}/api/auth/gen_code_source", AUTH_API_URL))
            .send()
            .await?
            .json::<Response<String>>()
            .await?
            .data,
    )
}

pub async fn get_img_code(code_source: &str) -> MyResult<ImgCode> {
    Ok(
        Request::post(&format!("{}/api/auth/gen_code", AUTH_API_URL))
            .json(&CodeSource {
                code: code_source.to_owned(),
            })?
            .send()
            .await?
            .json::<Response<ImgCode>>()
            .await?
            .data,
    )
}
